package com.hqyj.tmall.controller;


import com.github.pagehelper.PageInfo;
import com.hqyj.pojo.Product;
import com.hqyj.pojo.ProductImage;
import com.hqyj.tmall.service.ProductImageService;
import com.hqyj.tmall.service.TmallService;
import lombok.extern.slf4j.Slf4j;
import com.hqyj.manager.service.OrderService;
import com.hqyj.pojo.*;
import com.hqyj.tmall.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

@Controller
@RequestMapping("/tmall")
@Slf4j
public class IndexTmallController {
    @Resource
    private ProductImageService productImageService;

    @Autowired
    private TmallService tmallService;

    @Resource
    private UserService userService;
    @Resource
    private ProductService productService;
    @Resource
    private OrderItemService orderItemService;
    @Resource
    private CartItemService cartItemService;
    @Resource
    private MerchantService merchantService;
    @Resource
    private UserAddressService userAddressService;
    @Resource
    private OrderService orderService;


    @RequestMapping("/index")
    public String list(Model model) {
        //List<Product> productList=productService.findAll();

        Map<String, Object> bySeekName = tmallService.findBySeekName("", 1, 5);

        PageInfo <Product> pageInfo = (PageInfo<Product>) bySeekName.get("pageInfo");
        List<ProductImage>  pageImges = (List<ProductImage>) bySeekName.get("pageImges");

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("imgs",pageImges);

        //Product product=productList.get(6);
        //model.addAttribute("product",product);
        return "/tmall/home/index";
    }


    /**
     * 全局搜索
     * @return
     */
    @GetMapping("/seek")
    public String seek(
            @RequestParam(value = "seekName",required = false) String seekName,
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rowe", defaultValue = "5") Integer rowe,Model model){

        Map<String, Object> productMap = tmallService.findBySeekName(seekName,page,rowe);
        PageInfo <Product> pageInfo = (PageInfo<Product>) productMap.get("pageInfo");
        List<ProductImage>  pageImges = (List<ProductImage>) productMap.get("pageImges");

        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("imgs",pageImges);
        model.addAttribute("seekName",seekName);

        log.debug("请求到这里" + seekName);
        return "tmall/home/list";

    }


    @RequestMapping("/deta")//跳转详情页面（李勇注）
    public String deta(Model model,Integer id) {
       // System.out.println(id);
        Map<String, Object> map = productService.selectById(id);

        Product product = (Product) map.get("product");
        List<ProductImage> productImg = (List<ProductImage>) map.get("productImg");

        model.addAttribute("product",product);
        model.addAttribute("productimg",productImg);
        return "tmall/deta";
    }
    @RequestMapping("/addCartItem")
    @ResponseBody//添加购物车的一种产品（李勇注）
    public HashMap<String,Object> addCartItem(Model model, Integer id, Integer number, Integer total) {
        System.out.println(id);
        System.out.println(number);
        System.out.println(total);
        CartItem cartItem=new CartItem();
        cartItem.setProductId(id);
        cartItem.setNumber(number);
        cartItem.setTotal(total);
        HashMap<String,Object> map=new HashMap<>();
        String a= cartItemService.addByCartItem(cartItem);
            map.put("code",a);
//        Product product=productService.selectById(id);
//        model.addAttribute("product",product);
        return map;
    }
//    @RequestMapping("/cart")//(李勇)
//    public String cart(Model model) {//跳转购物车（李勇注）
//
//        List<CartItem> cartItemList=cartItemService.selectAllCartItem();
//            model.addAttribute("list",cartItemList);
//        return "tmall/cart";
//    }

    @RequestMapping("/cart2")//(李勇)
    public String cart2(Model model) {//跳转购物车（李勇注）

        List<CartItem> cartItemList=cartItemService.selectAllCartItem();//查看购物车全部产品
        List<Integer> list=new ArrayList<>();

        for (CartItem cartItem : cartItemList) {
           list.add(cartItem.getProducts().getMerchantId());
        }
      List<Merchant> merchantList=merchantService.selectByListId(list);

        model.addAttribute("list",cartItemList);
        model.addAttribute("list2",merchantList);
       // System.out.println(merchantList.get(0).getId());
        //System.out.println(cartItemList.get(0).getProducts().getId());

        return "tmall/cart2";
    }
    @RequestMapping("/oderItem")//(李勇)
    @ResponseBody//添加订单项（李勇注）
    public HashMap<String,Object> oderItem(Model model,String oneTotal,String oneNumber,
                           String total_money,String total_count,int[] check_val) {//跳转购物车（李勇注）
//        System.out.println("总的"+total_money);
//        System.out.println("总的"+total_count);
//        System.out.println("单的"+oneTotal);
//          System.out.println("单的"+oneNumber);
//        System.out.println("产品"+check_val[0]);
//        System.out.println("产品"+check_val[1]);
        HashMap<String,Object> map=new HashMap<>();
        List<OrderItem> list=new ArrayList<>();
        String[] number=oneNumber.split(",");
        String[] total=oneTotal.split(",");
        for (int i = 0; i <number.length ; i++) {
            OrderItem orderItem=new OrderItem();
            orderItem.setNumber(Integer.valueOf(number[i]));
            orderItem.setTotal(Integer.valueOf(total[i]));
            orderItem.setProductId(check_val[i]);
            orderItem.setUserId(1);//假装从前端传了一个UserId过来
            list.add(orderItem);
        }
//        for (OrderItem orderItem : list) {
//            System.out.println(orderItem);
//        }
        int a=orderItemService.addsOrderItem(list);

       if(a>0){
           map.put("code","添加成功");
       }else{
           map.put("code","添加失败");
       }
return map;
    }
    @RequestMapping("/order")//(李勇)
    public String order(Model model,String oneTotal,String oneNumber,
                        String total_money,String total_count,int[] check_val) {//
                //假装购物车传了一个userid过来
        Integer userId=1;
        User user=userService.selectAllByUserId(userId);//根据UserId查找对应的地址集合（李勇）
        List<OrderItem> list2=new ArrayList<>();
        List<Integer> list3=new ArrayList<>();
//        System.out.println(user);
        String[] number=oneNumber.split(",");
        String[] total=oneTotal.split(",");
        for (int i = 0; i <number.length ; i++) {
            OrderItem orderItem=new OrderItem();
            orderItem.setNumber(Integer.valueOf(number[i]));
            orderItem.setTotal(Integer.valueOf(total[i]));
            orderItem.setProductId(check_val[i]);
            orderItem.setUserId(1);//假装从前端传了一个UserId过来
            list2.add(orderItem);
        }
        for (int i = 0; i <check_val.length ; i++) {
            list3.add(check_val[i]);
        }
        List<Product> productList=productService.selectByListId(list3);
        model.addAttribute("list",user);//用户的地址信息
        model.addAttribute("list2",list2);//产品的采购信息
        model.addAttribute("list3",productList);//产品的基本信息
        model.addAttribute("money",total_money);//总价
        model.addAttribute("total_count",total_count);//总数

        return "tmall/order";
    }
    @RequestMapping("/orderSub")//(李勇)
    @ResponseBody//添加订单（李勇注）
    public HashMap<String,Object> orderSub(Model model,String userName,String phone,String address,String detailed,Integer userId,
                           int[] oneMoney,int[] oneNumber,int[] oneTotal,int[] productId,int Total,String userMessage) {//跳转购物车（李勇注）
        System.out.println(userId+"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        HashMap<String,Object> map=new HashMap<>();
            //首先添加订单项
        int Len=detailed.length();//得到字符串的完整长度
        int start = Len-7;
//        System.out.println(start);
//        System.out.println(Len);
        String post=detailed.substring(start,Len-1);//得到邮编
       // System.out.println(post);
        detailed=detailed.substring(0,Len-8);//得到详细地址
        String address2=address+","+detailed;//所有地址
        Random random = new Random();
        int a=random.nextInt(999999999)+100000000;//产生一个9位数的随机数
        String orderCode= UUID.randomUUID()+""+a;//生成了一个特殊的订单号
        //System.out.println(orderCode);
        Order order=new Order();
        order.setOrderCode(orderCode);
        order.setUserId(userId);
        order.setAddress(address2);
        order.setPost(post);
        order.setReceiver(userName);
        order.setMobile(phone);
        order.setUserMessage(userMessage);
        order.setCreateDate(new Date());
        order.setStatus("1");
        order.setPostMethod("顺丰物流");
        order.setPostage(0.00);
        order.setTotal(Double.valueOf(Total));
        int flag=orderService.addOneByOrder(order);
      //  System.out.println(flag);
      //  System.out.println(order.getId());
        //添加订单项
        if(flag>0){
            List<OrderItem> list=new ArrayList<>();
            for (int i = 0; i <productId.length ; i++) {
                OrderItem orderItem=new OrderItem();
                orderItem.setProductId(productId[i]);
                orderItem.setTotal(oneTotal[i]);
                orderItem.setNumber(oneNumber[i]);
                orderItem.setUserId(userId);
                orderItem.setOrderId(order.getId());
                list.add(orderItem);
            }
            int i = orderItemService.addsOrderItem(list);
            System.out.println(i+"orderItem");
            if(i<0){
                map.put("code","訂單項添加失敗");
            }
        }else{
            map.put("code","訂單添加失敗");
        }
        map.put("address",address2);//地址
        map.put("total",Total);//总价
        map.put("username",userName);//，名字
        map.put("orderCode",orderCode);//订单号
        return map;

    }
    @RequestMapping("/parment")//(李勇)
    public String cart(Model model,String address,String total,String username,String orderCode) {//跳转付款（李勇注）
        System.out.println(address);
        System.out.println(total);
        System.out.println(username);
        System.out.println(orderCode);
        model.addAttribute("address",address);
        model.addAttribute("total",total);
        model.addAttribute("username",username);
        model.addAttribute("orderCode",orderCode);
        return "tmall/payment";
    }
    @RequestMapping("/cartDelete")//(李勇)
    @ResponseBody//
    public HashMap<String,Object> cartDelete(Model model,Integer userId) {//删除购物车
        HashMap<String,Object> map=new HashMap<>();
                int a=cartItemService.delectByProductId(userId);
                if(a>0){
                    map.put("code","删除成功");
                }else {
                    map.put("code","删除失败");
                }
        return map;
    }
}
